import { command } from "@/config/api";
import { useStore } from "@/store/context";
import { Action } from "@/store/type";
import {
  Badge,
  Box,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Typography
} from "@mui/material";
import { getName, getVersion } from "@tauri-apps/api/app";
import { Channel, invoke } from "@tauri-apps/api/core";

function DownloadView() {
  const { state, dispatch } = useStore();
  const [open, setOpen] = useState(false);
  const [progress, setProgress] = useState<number | undefined>();

  const checkUpdate = async () => {
    const resp = await invoke<boolean>(command.check_update);
    dispatch({ type: Action.SET_HAS_UPDATE, payload: resp });
  };

  const onEvent = new Channel<number>();
  onEvent.onmessage = (message) => {
    console.log("progress", message);
    setProgress(message);
  };

  const download = async () => {
    invoke(command.download, { onEvent });
    setOpen(false);
  };

  const checkBtn = (
    <Button size="small" onClick={checkUpdate}>
      检查更新
    </Button>
  );

  const downloadBtn = (
    <>
      <Badge color="error" variant="dot" invisible={!state.hasUpdate}>
        <Button disabled={progress !== undefined} size="small" onClick={() => setOpen(true)}>
          下载更新
        </Button>
      </Badge>
      {progress !== undefined ? (
        <Typography variant="caption" component="div" sx={{ color: "text.secondary" }}>
          {progress}%
        </Typography>
      ) : (
        <></>
      )}
    </>
  );

  return (
    <>
      {state.hasUpdate ? downloadBtn : checkBtn}

      <Dialog
        open={open}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
      >
        <DialogTitle id="alert-dialog-title">更新</DialogTitle>
        <DialogContent>
          <DialogContentText id="alert-dialog-description">是否要下载更新？</DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpen(false)}>Cancel</Button>
          <Button variant="contained" onClick={download} autoFocus>
            OK
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
}

export default function About() {
  const [info, setInfo] = useState<{
    name: string;
    version: string;
  }>();

  useEffect(() => {
    Promise.all([getName(), getVersion()]).then(([name, version]) => {
      setInfo({
        name,
        version
      });
    });
  }, []);

  return (
    <>
      <Box sx={{ width: "100%", display: "flex", flexDirection: "column", px: 4 }}>
        <Box sx={{ fontSize: "20px", fontWeight: 600 }}>About</Box>
        <Box sx={{ mt: 2, p: 2 }}>
          <p>Name: {info?.name}</p>
          <Box sx={{ display: "flex", gap: 2, alignItems: "center" }}>
            Version: {info?.version}
            <DownloadView />
          </Box>
        </Box>
      </Box>
    </>
  );
}
